package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;

@Service("douyinPayService")
public class DouYinPayServiceImpl extends BasePayment {





    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        JSONObject qryObj = new JSONObject();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dy_ck = userRecipientInfo.getCookie();
//        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
//        String dy_ck = cookieObj.getString("dy_ck");
        String fq = dy_ck.split("s_v_web_id=")[1].split(";")[0];
        //https://www.douyin.com/webcast/wallet_api/diamond_buy_external_safe/?diamond_id=888888&source=8&way=0&aid=1128&short_id=xiannv1028.&fp=verify_l4zkcj96_ApzyQR18_XA03_4Swg_B6u7_uHgn16LRGvgX&customized_price=5000
        String url = "https://webcast.amemv.com/webcast/wallet_api/diamond_buy_external_safe/?diamond_id=888888&source=5&way=0&aid=1128&short_id="+userRecipientInfo.getChannelAccount()+"&fp="+fq+"&platform=android&customized_price="+orderInfo.getMoney();
        headerMap.put("cookie",dy_ck);
        headerMap.put("user-agent","Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");

        logger.info("抖音生成收银台URL："+url);
        JSONObject ipObj = commonService.getPoxyIp(userRecipientInfo.getProvince());
        String ip = ipObj.getString("ip");
        String port = ipObj.getString("port");
//        cn.hutool.http.HttpResponse dyHttpRes = HttpUtil.createGet(url).header("cookie",dy_ck).execute();
//        JSONObject dyHttpResObj = JSONObject.parseObject(dyHttpRes.body());
        logger.info("dy_ck=========："+dy_ck);

//        org.apache.http.client.fluent.Request request = org.apache.http.client.fluent.Request.Get(url);
//        org.apache.http.HttpResponse httpResponse = request.execute().returnResponse();
//        request.setHeader("Cookie", dy_ck);
//        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
//        httpResponse = request.execute().returnResponse();
//        String dyHttpRes = "";
//        if (httpResponse.getEntity() != null) {
//            dyHttpRes = EntityUtils.toString(httpResponse.getEntity());
//        }
        String dyHttpRes = HttpUtils.sendPostRequest(url,"",headerMap);

//        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,dy_ck,"SYB",ip+":"+port);
        logger.info("抖音生成收银台=========："+dyHttpRes);
        JSONObject dyHttpResObj = JSONObject.parseObject(dyHttpRes);
        if(dyHttpResObj.getIntValue("status_code")!=0){
            jsonObject.put("code","100");
            jsonObject.put("msg",dyHttpResObj.getJSONObject("data").getString("prompts"));
            return jsonObject;
        }
        /**
        String params = dyHttpResObj.getJSONObject("data").getString("params");
        String appId = getParamByUrl(params,"app_id");
        String merchant_id = getParamByUrl(params,"merchant_id");
        String out_order_no = getParamByUrl(params,"out_order_no");
        String sign = getParamByUrl(params,"sign");
        String timestamp = getParamByUrl(params,"timestamp");
        String total_amount = getParamByUrl(params,"total_amount");
        String trade_no = getParamByUrl(params,"trade_no");
        String uid = getParamByUrl(params,"uid");
        JSONObject bizContentObj = new JSONObject();
        JSONObject riskInfoObj = new JSONObject();
        riskInfoObj.put("device_platform","android");
//        riskInfoObj.put("os_version","");
//        riskInfoObj.put("version_code","");
//        riskInfoObj.put("did","");
//        riskInfoObj.put("iid","");
//        riskInfoObj.put("aid","");
//        riskInfoObj.put("app_name","");
//        riskInfoObj.put("device_platform","");
//        riskInfoObj.put("device_type","");
//        riskInfoObj.put("user_agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36");
        qryObj.put("trade_no",trade_no);

        JSONObject paramObj = new JSONObject();
        JSONObject extsObj = new JSONObject();
        extsObj.put("qrcode_validity_seconds","60");
        paramObj.put("app_id",appId);
//        paramObj.put("exts",extsObj);
        paramObj.put("encodeType","base64");

        paramObj.put("merchant_id",merchant_id);
        paramObj.put("out_order_no",out_order_no);
        paramObj.put("return_scheme","");
        paramObj.put("return_url","https://aweme.snssdk.com/falcon/webcast_douyin/page/recharge_wx/index.html");
        paramObj.put("sign",sign);
        paramObj.put("sign_type","MD5");
        paramObj.put("switch","00");
        paramObj.put("timestamp",timestamp);
        paramObj.put("total_amount",total_amount);
        paramObj.put("trade_no",trade_no);
        paramObj.put("trade_type","H5");
        paramObj.put("uid",uid);
        paramObj.put("open_id","");
        bizContentObj.put("params",paramObj);
        String biz_content="scene=h5&risk_info="+ URLEncoder.encode(riskInfoObj.toString())+"&biz_content="+URLEncoder.encode(bizContentObj.toJSONString());
        String paytypeInfo = HttpUtils.sendPostRequest("https://tp-pay.snssdk.com/gateway-cashier2/tp/cashier/trade_create",biz_content,headerMap);
        JSONObject paytypeInfoObj = JSONObject.parseObject(paytypeInfo);
        logger.info("抖音生成收银台2："+paytypeInfoObj);
        if(!"CA0000".equalsIgnoreCase(paytypeInfoObj.getString("code"))){
            jsonObject.put("code","100");
            jsonObject.put("msg",paytypeInfoObj.getJSONObject("error").getString("msg"));
            return jsonObject;
        }
//        riskInfoObj = new JSONObject();
//        riskInfoObj.put("user_agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36");

        String process = paytypeInfoObj.getString("process");
        qryObj.put("process",process);
        String processBase64 = Base64Util.encode(process);
        //{"trade_no":"SP2022062921135329619532947604","ptcode":"alipay","ptcode_info":{"bank_card_id":"","business_scene":"","return_url":"https://tp-pay.snssdk.com/cashdesk/?cj_new_api=1&cj_source=alipay&cj_trade_no=SP2022062921135329619532947604&cj_process=eyJ0eXBlIjoiY2FjaGUiLCJkYXRhIjoiZGZhZTY1ZGY5NmQ1NGI0MGZmNTY2M2EyN2U4Yzk1MmE4NmNlYzY1NmNiZDdhMmNiMmZkNWJjMmY4NWE5NGU1NyJ9&cj_remain_time=5"}}
        bizContentObj = new JSONObject();
        bizContentObj.put("trade_no",trade_no);
        bizContentObj.put("ptcode","alipay");
        JSONObject ptcodeInfoObj = new JSONObject();
//        ptcodeInfoObj.put("icon_url","https://lf3-static.bytefae.com/obj/static-assets/4fbb3fd72b1c6911c0d44d85c17ccada.png");
//        ptcodeInfoObj.put("mark","");
//        ptcodeInfoObj.put("msg","");
//        ptcodeInfoObj.put("paytype_item_info","");
//        ptcodeInfoObj.put("ptcode","alipay");
//        ptcodeInfoObj.put("recommended_btn_msg","");
//        ptcodeInfoObj.put("stable_status","1");
//        ptcodeInfoObj.put("status","1");
//        ptcodeInfoObj.put("sub_title","");
//        ptcodeInfoObj.put("sub_title_color","");
//        ptcodeInfoObj.put("tips_msg","");
//        ptcodeInfoObj.put("title","");
//        ptcodeInfoObj.put("code","alipay");
//        ptcodeInfoObj.put("active","1");
//        ptcodeInfoObj.put("limit","1");
//
//        ptcodeInfoObj.put("return_url","https://tp-pay.snssdk.com/cashdesk_pc/result?app_id="+appId+"&trade_no="+trade_no+"&process_info="+processBase64);
        ptcodeInfoObj.put("bank_card_id","");
        ptcodeInfoObj.put("business_scene","");
        ptcodeInfoObj.put("return_url","https://tp-pay.snssdk.com/cashdesk/?cj_new_api=1&cj_source=alipay&cj_trade_no="+trade_no+"&cj_process=="+processBase64+"&cj_remain_time=5");
        bizContentObj.put("ptcode_info",ptcodeInfoObj);
        biz_content = "scene=h5&risk_info="+ URLEncoder.encode(riskInfoObj.toString())+"&channel_support_scene=ALI_H5&biz_content="+URLEncoder.encode(bizContentObj.toString())+"&process="+URLEncoder.encode(process);
        paytypeInfo = HttpUtils.sendPostRequest("https://tp-pay.snssdk.com/gateway-cashier2/tp/cashier/trade_confirm",biz_content,headerMap);
        logger.info("抖音生成收银台3："+paytypeInfo);
        paytypeInfoObj = JSONObject.parseObject(paytypeInfo);
        if(!"CA0000".equalsIgnoreCase(paytypeInfoObj.getString("code"))){
            jsonObject.put("code","100");
            jsonObject.put("msg",paytypeInfoObj.getJSONObject("error").getString("msg"));
            return jsonObject;
        }
        orderInfo.setQrcodeTxt(qryObj.toJSONString());
        orderInfoService.updateById(orderInfo);
        String payUrl = paytypeInfoObj.getJSONObject("data").getJSONObject("pay_params").getJSONObject("data").getString("url");

        jsonObject.put("payUrl",payUrl);
        jsonObject.put("orderNo",trade_no);**/
        jsonObject.put("code","200");
        return jsonObject;
    }

    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        return null;
    }
    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }

}
